package com.zhouyu;

import com.zhouyu.service.*;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
//		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.getBeanFactory().addEmbeddedValueResolver(strVal -> {
			if (strVal.equals("${xxx}")) {
				return "hello xxx";
			}
			return applicationContext.getEnvironment().resolvePlaceholders(strVal);
		});
		applicationContext.register(AppConfig.class);

		// 添加beanDefinition
		AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
		beanDefinition.setBeanClass(MemberService.class);
		beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(new OrderService());
		// 设置自动获取构造方法
//		beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
		beanDefinition.setInstanceSupplier(() -> {
			User user = new User();
			user.setName("xiaogang");
			return user;
		});
		applicationContext.registerBeanDefinition("memberService", beanDefinition);


		applicationContext.refresh();
		User memberService = (User) applicationContext.getBean("memberService");
		memberService.toString();


//		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//		UserService userService = (UserService) applicationContext.getBean("userService");
//		AbstractUserService abstractUserService = (AbstractUserService) applicationContext.getBean("abstractUserService");
//		abstractUserService.test();

//		userService.test();

		// 测试@Value
//		ValueTest valueTest = applicationContext.getBean("valueTest", ValueTest.class);
//		valueTest.printOrderService();

		// 依赖注入测试泛型
//		GenericsTest genericsTest = applicationContext.getBean("genericsTest", GenericsTest.class);
//		genericsTest.test();

		// 测试推断构造
//		MemberService memberService = (MemberService) applicationContext.getBean("memberService", new OrderService());
//		memberService.test();

//		applicationContext.close();
		// 注册一个关闭钩子，来实现bean的销毁

		applicationContext.registerShutdownHook();
	}
}
